# -*- coding: gb2312 -*-
"""
Created on Tue Mar 05 17:56:31 2013

@author: Admin
"""

import time
import threading


class _TimerThread(threading.Thread):
    """ """
    METHOD_TIME_OUT =   "METHOD_TIME_OUT_2013_03"
    METHOD_INTERVAL =   "METHOD_INTERVAL_2013_03"
    
    def __init__(self,func,delay,method,*args):
        """ """
        threading.Thread.__init__(self,name="_TimerThread")
        self.__func     = func
        self.__delay    = delay
        self.__method   = self.__checkMethod(method)
        self.__args     = args
        self.__isend    =   False
    def __checkMethod(self,method):
        """ """
        if method == _TimerThread.METHOD_TIME_OUT:
            return 1
        elif method == _TimerThread.METHOD_INTERVAL:
            return 2
        else:
            return 0
            
    def run(self):
        """ """
        if self.__method == 1:
            time.sleep(self.__delay)
            if self.__isend:
                return 
            return self.__func(self.__args)
        elif self.__method == 2:
            while not self.__isend:
                time.sleep(self.__delay)
                if not self.__isend:
                    self.__func(self.__args)
    
    def stop(self):
        """ """
        self.__isend = True

def setTimeOut(func,delay,*args):
    """ """
    tm = _TimerThread(func,delay,_TimerThread.METHOD_TIME_OUT,args)
    tm.start()
    return tm

def setInterval(func,delay,*args):
    """ """
    tm = _TimerThread(func,delay,_TimerThread.METHOD_INTERVAL,args)
    tm.start()
    return tm
    
def removeTimeFunc(timeID):
    """ """
    if isinstance(timeID,_TimerThread):
        timeID.stop()
        return True
        
def test(*args):
    print "test"
    
if __name__ == "__main__":
    #a = setTimeOut(test,4,None)
    a = setInterval(test,1,None)
    time.sleep(5)
    removeTimeFunc(a)